package org.jiajie.coffeecodes.concurrent.pattern.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @author jay
 */
public class TwoPhaseTermination {
    private Thread monitor;
    public void start(){
        monitor = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                if (thread.isInterrupted()){
                    // TODO: 线程终止前的操作
                    System.out.println("Thread is interrupting...");
                    break;
                }
                try {
                    // TODO: 线程执行的业务代码
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    thread.interrupt();
                }
            }
            System.out.println("Thead was interrupted");
        }, "monitor");
        monitor.start();
    }

    public void stop(){
        monitor.interrupt();
    }
}
